package com.atguigu.day04;

import com.atguigu.util.ClickEvent;
import com.atguigu.util.ClickSource;
import com.atguigu.util.UserViewCountPerWindow;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

// Example2的底层实现
public class Example4 {
    public static void main(String[] args) {
        var env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .addSource(new ClickSource())
                .keyBy(r -> r.username)
                .process(new KeyedProcessFunction<String, ClickEvent, UserViewCountPerWindow>() {
                    private final long windowSize = 5000L;

                    // key: 窗口信息
                    // value: 窗口中的累加器
                    private MapState<Tuple2<Long, Long>, Integer> mapState;

                    @Override
                    public void open(Configuration parameters) {
                        mapState = getRuntimeContext().getMapState(
                                new MapStateDescriptor<>(
                                        "windowInfo-accumulator",
                                        Types.TUPLE(Types.LONG, Types.LONG),
                                        Types.INT
                                )
                        );
                    }

                    @Override
                    public void processElement(ClickEvent clickEvent, Context context, Collector<UserViewCountPerWindow> collector) throws Exception {
                        long currTs = context.timerService().currentProcessingTime();
                        long winStart = currTs - currTs % windowSize;
                        long winEnd = winStart + windowSize;
                        var windowInfo = Tuple2.of(winStart, winEnd);

                        if (!mapState.contains(windowInfo)) {
                            mapState.put(windowInfo, 1);
                        } else {
                            mapState.put(windowInfo, mapState.get(windowInfo) + 1);
                        }

                        context.timerService().registerProcessingTimeTimer(winEnd - 1L);
                    }

                    @Override
                    public void onTimer(long timestamp, OnTimerContext ctx, Collector<UserViewCountPerWindow> out) throws Exception {
                        long winEnd = timestamp + 1L;
                        long winStart = winEnd - windowSize;
                        var username = ctx.getCurrentKey();
                        var count = mapState.get(Tuple2.of(winStart, winEnd));
                        out.collect(new UserViewCountPerWindow(username, count, winStart, winEnd));

                        mapState.remove(Tuple2.of(winStart, winEnd));
                    }
                })
                .print();

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
